`
You can download this script from https://github.com/dolevf/Black-Hat-
Bash/blob/master/ch02/test_if_file_exists.sh. Save the file and execute it. You
should see the flow_control_with_if.txt file in your current directory when you run
ls.
Listing 2-2 shows a different way of achieving the same outcome; it uses the
not operator (!) to check whether a directory doesn’t exist, and if so, creates it.
This example has fewer lines of code and eliminates the need for an else block
altogether.
#!/bin/bash
FILENAME="flow_control_with_if.txt"
if [[ ! -f "${FILENAME}" ]]; then
touch "${FILENAME}"
fi
Listing 2-2
An example of a file test using a negative check
Save and run this script. It should create a directory named downloads if this
directory wasn’t already present.
Let’s explore if conditions that use some of the other kinds of test operators
we’ve covered. Listing 2-3 shows an example of a string comparison test. It tests
whether two variables are equal by performing string comparison with the equal-to
operator (==).
#!/bin/bash
VARIABLE_ONE="nostarch"
VARIABLE_TWO="nostarch"
if [[ "${VARIABLE_ONE}" == "${VARIABLE_TWO}" ]]; then
echo "They are equal!"
else
echo "They are not equal!"
fi
Listing 2-3
A string comparison test comparing two string variables
The script will compare the two variables, both of which have the value
nostarch, and print They are equal! by using the echo command. It is
available at https://github.com/dolevf/Black-Hat-
Bash/blob/master/ch02/string_comparison.sh.
Next is an example of an integer comparison test, which takes two integers
and checks which one is the larger number.
#!/bin/bash
VARIABLE_ONE="10"
VARIABLE_TWO="20"
Black Hat Bash (Early Access) © 2023 by Dolev Farhi and Nick Aleks